package chch;

import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.HashMap;

import javax.swing.JFrame;

public class App extends JFrame {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private int n = 3, m = 3;
	private HashMap<String, String> table;
	private HashMap<Integer, Pinyin> pinyins;

	private String tablePath = "pinyin/table";

	public App() {

		readTable(tablePath);
		setDefaultCloseOperation(DISPOSE_ON_CLOSE);
		this.setLayout(new GridLayout(m, n));
		Pinyin pinyin = null;
		addKeyListener(new KeyListener() {

			@Override
			public void keyTyped(KeyEvent arg0) {

				if (arg0.getKeyChar() >= '1' && arg0.getKeyChar() <= '9') {
					pinyins.get(Character.getNumericValue(arg0.getKeyChar()))
							.getPanel().flip();
					repaint();
				}

			}

			@Override
			public void keyReleased(KeyEvent arg0) {
				// TODO Auto-generated method stub

			}

			@Override
			public void keyPressed(KeyEvent arg0) {
				// TODO Auto-generated method stub

			}
		});

		pinyins = new HashMap<Integer, Pinyin>();
		for (int i = 0; i < n*m; i++) {
			String s = (String) table.keySet().toArray()[(int) Math.floor(Math
					.random() * table.size())];
			pinyin = new Pinyin(table.get(s), s);
			this.add(pinyin.getPanel());
		}

		setPreferredSize(new Dimension(21 + n
				* pinyin.getPanel().getImage().getWidth(), 40 + m
				* pinyin.getPanel().getImage().getHeight()));
		pack();
		repaint();
		setLocationRelativeTo(null);
		setVisible(true);
		
	}

	private void readTable(String path) {

		InputStream fis;
		BufferedReader br;
		String url;

		table = new HashMap<String, String>();

		try {
			fis = new FileInputStream(path);
			br = new BufferedReader(new InputStreamReader(fis,
					Charset.forName("UTF-8")));

			while ((url = br.readLine()) != null) {
				String pinyin = br.readLine();
				table.put(url, pinyin);
			}

			br.close();
			br = null;
			fis = null;

		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	public static void main(String[] args) {
		new App();
	}

}
